# -*- coding: utf-8 -*-
# @Time    : 2021/9/3 15:51
# @Author  : huangwei
# @File    : video_functions.py
# @Software: PyCharm
import os

import cv2

from method import extract_from_video, get_video_param, split_video


def video_extract_watermark( input_filepath, output_filepath, watermark_path, tmp_directory ):
    """
    1. 截取一段长35s的视频，确保跨越插入水印的视频间隔长度
    2. 将视频分成多个5s长的
    """
    # 取出视频流并进行帧内编码并转为yuv420p格式
    video_stream_path = "{0}/video.mp4".format(tmp_directory)
    os.system("ffmpeg -y -i {0} -vcodec copy -an {1} -loglevel quiet".format(input_filepath, video_stream_path))
    print("3.提取视频流存储到：", video_stream_path)

    intra_filepath = "{0}/intra.mp4".format(tmp_directory)
    os.system("ffmpeg -y -i %s -strict -2 -qscale 0 -pix_fmt yuv420p -intra %s -loglevel quiet" % (
        video_stream_path, intra_filepath))
    print("视频进行帧内编码：", intra_filepath)

    return extract_from_video(intra_filepath, output_filepath, watermark_path, tmp_directory)


def compress_video( input_filepath, compress_output_filepath ):
    """
    对视频进行压缩，将视频转换成 800*400 或 400*800 分辨率的视频
    :param input_filepath:
    :param compress_output_filepath:
    :return:
    """
    video_param = get_video_param(input_filepath)
    width = video_param['width']
    height = video_param['height']

    # 需要是偶数
    if width >= height:
        new_width = 800
        new_height = 400
    else:
        new_height = 800
        new_width = 400

    os.system("ffmpeg -y -i {0} -s {1}x{2} {3} -loglevel quiet".format(input_filepath, new_width, new_height,
                                                                       compress_output_filepath))


def video_add_visual_watermark( input_filepath, watermark_path, output_filepath, tmp_directory ):
    # 1. 对视频进行压缩
    (_, tmp_filename) = os.path.split(output_filepath)

    compress_output_filepath = "{0}/compress_{1}".format(tmp_directory, tmp_filename)  # 压缩视频路径
    only_center_filepath = "{0}/only_center_{1}".format(tmp_directory, tmp_filename)  # 只插入一个水印的路径
    two_watermark_filepath = "{0}/two_watermark_{1}".format(tmp_directory, tmp_filename)  # 插入两个水印的路径

    compress_video(input_filepath, compress_output_filepath)  # 压缩视频
    print("8.压缩视频！")

    # 读取视频的长宽
    video_param = get_video_param(compress_output_filepath)
    width = video_param['width']
    height = video_param['height']

    # 读取水印的大小，水印大小固定
    watermark = cv2.imread(watermark_path)
    watermark_width = watermark.shape[1]
    watermark_height = watermark.shape[0]

    # 2. 在中间加入水印 的坐标
    pos_x = int((width - watermark_width) / 2)
    pos_y = int((height - watermark_height) / 2)

    os.system(
        "ffmpeg -y -i {0} -i {1} -filter_complex \"[1:v]colorkey=0x000000:0.5:1.0[logo];[0:v][logo]overlay=x={2}:y={3}\" {4} -loglevel quiet".format(
            compress_output_filepath,
            watermark_path,
            pos_x, pos_y,
            only_center_filepath))
    print("9.中间位置插入水印！")

    # 判断插入第二个水印的坐标
    if width <= height:
        # 若高大于宽则在左上角插入水印
        pos_x = 5
        pos_y = 5

    else:
        # 若宽大于高则在右下角插入水印
        pos_x = width - watermark.shape[1] - 5
        pos_y = height - watermark.shape[0] - 5

    # 插入第二个水印
    os.system(
        "ffmpeg -y -i {0} -i {1} -filter_complex \"[1:v]colorkey=0x000000:0.5:1.0[logo];[0:v][logo]overlay=x={2}:y={3}\" {4} -loglevel quiet".format(
            only_center_filepath,
            watermark_path,
            pos_x, pos_y,
            two_watermark_filepath))

    # 将生成的文件复制到目标文件中，防止插入水印时间过长目标文件使用出错
    os.system("mv {0} {1}".format(two_watermark_filepath, output_filepath))
    print("明水印插入完成：", output_filepath)


def video_insert_watermark( input_filepath, watermark_filepath, output_filepath, tmp_directory ):
    """
    视频插入暗水印
    :param input_filepath:
    :param watermark_filepath:
    :param output_filepath:
    :param tmp_directory:
    :return:
    """
    # 2. 将视频进行帧内编码并转为yuv420p格式
    intra_filepath = "{0}/intra.mp4".format(tmp_directory)
    os.system("ffmpeg -y -i %s -strict -2 -qscale 0 -pix_fmt yuv420p -intra %s -loglevel quiet" % (
        input_filepath, intra_filepath))
    print("12.视频进行帧内编码：", intra_filepath)

    # 取出视频流的多个参数不用每次都取提高速度
    video_param = get_video_param(intra_filepath)

    # 判断是否存在音频流，存在的话将其分离出来存储到临时文件夹中
    if video_param['audio']:
        audio_stream_path = "{0}/audio.m4a".format(tmp_directory)
        os.system("ffmpeg -y -i {0} -acodec copy -vn {1} -loglevel quiet".format(intra_filepath, audio_stream_path))

    # 视频流存储路径
    video_stream_path = "{0}/video.mp4".format(tmp_directory)
    os.system("ffmpeg -y -i {0} -vcodec copy -an {1} -loglevel quiet".format(intra_filepath, video_stream_path))
    print("13.分离音视频流！")

    # 每 30s 插入 1s 的水印
    video_stream_embed_path = "{0}/video_embed.mp4".format(tmp_directory)
    split_video(video_stream_path, video_stream_embed_path, watermark_filepath, video_param, tmp_directory)

    # 音频视频合并
    tmp_ouput_filepath = "{0}/tmp_output.mp4".format(tmp_directory)
    if video_param['audio']:
        os.system(
            "ffmpeg -y -i {0} -i {1} -c copy {2} -loglevel quiet".format(video_stream_embed_path, audio_stream_path,
                                                                         tmp_ouput_filepath))
    else:
        os.system("cp {0} {1}".format(video_stream_embed_path, tmp_ouput_filepath))

    # 将生成的视频复制到 output 中，增加这一步可以避免未完全生成完合并文件就使用输出文件
    os.system("mv {0} {1}".format(tmp_ouput_filepath, output_filepath))
    print("水印插入完成：", output_filepath)
